import os
import datetime

from util import Util
from openpyxl import load_workbook
from write.AbstractWrite import AbstractWrite


class CargoEvaluation(AbstractWrite):
	def __init__(self):
		super().__init__()

	def setDic(self, cargoTextDic, cargoUnderlineDic, shipTextDic, shipUnderlineDic):
		self.cargoTextDic = cargoTextDic
		self.cargoUnderlineDic = cargoUnderlineDic
		self.shipTextDic = shipTextDic
		self.shipUnderlineDic = shipUnderlineDic

	def write(self):
		oldPath, newPath = self._getPath("合同评审表")
		workbook = load_workbook(filename=oldPath)

		sheet = workbook["1"]# 获取sheetV

		Util.tryWrite2Excel(sheet, "B3", self.cargoUnderlineDic, "航次")# 修改船名
		Util.tryWrite2Excel(sheet, "B4", self.cargoUnderlineDic, "航次", 1)# 修改航次
		Util.tryWrite2Excel(sheet, "D3", self.cargoTextDic, "甲方")# 修改租家
		sheet["B5"] = '{cargoType}，{volume}'.format(cargoType=self.cargoUnderlineDic["货种"][0],
		                                            volume=self.cargoTextDic["货量"].split("，")[0].replace(" ", ""))# 修改货物名称
		sheet["B8"] = self.cargoTextDic["受载期"].split("。")[0].replace(" ", "")# 修改受载期
		Util.tryWrite2Excel(sheet, "E7", self.cargoTextDic, "装货港")# 修改受装港
		Util.tryWrite2Excel(sheet, "E8", self.cargoTextDic, "卸货港")# 修改卸货港

		"""修改日期"""
		temp = self.cargoTextDic["签约日期"].replace(" ", "")
		sheet["E2"].value = datetime.datetime.strptime(temp, "%Y年%m月%d日")

		workbook.save(newPath)

	def _getPath(self, modelName):
		oldName = ""
		outputPath = os.path.join(self.outputDir,
		                          "{shipName}V{voyage}".format(shipName=self.shipUnderlineDic["航次"][0],
		                                                       voyage=self.shipUnderlineDic["航次"][1]))
		if not os.path.exists(outputPath):
			os.makedirs(outputPath)
		files = os.listdir(self.modelPath)
		files.sort()

		for file in files:
			if os.path.splitext(file)[0] == modelName:
				oldName = file
		newname = "货附件2：{shipName}V{voyage}{oldname}".format(shipName=self.shipUnderlineDic["航次"][0],
		                                                        voyage=self.shipUnderlineDic["航次"][1],
		                                                        oldname=oldName)
		newPath = os.path.join(outputPath, newname)
		oldPath = os.path.join(self.modelPath, oldName)

		return oldPath, newPath
